import Vue from 'vue'
import VueRouter from 'vue-router'

// 二级路由
import Home from '@/views/layout/home.vue'
import Category from '@/views/layout/category.vue'
import Cart from '@/views/layout/cart.vue'
import User from '@/views/layout/user.vue'

import store from '@/store'
// 一级路由
// 懒加载
const Login = () => import('@/views/login')
const Layout = () => ('@/views/layout')
const Search = () => ('@/views/search/index.vue')
const List = () => ('@/views/search/list.vue')
const ProDetail = () => ('@/views/prodetail')
const Pay = () => ('@/views/pay')
const MyOrder = () => ('@/views/myorder')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      // 重定向
      redirect: '/home',
      children: [
      // 二级路由
        { path: 'home', component: Home },
        { path: 'category', component: Category },
        { path: 'cart', component: Cart },
        { path: 'user', component: User }

      ]
    },
    { path: '/search', component: Search },
    { path: '/searchlist', component: List },
    { path: '/prodetail/:id', component: ProDetail },
    { path: '/pay', component: Pay },
    { path: '/myorder', component: MyOrder }
  ]
})

// 智慧商城项目，大部分页面，游客都可以直接访问,
// 如遇到需要登录才能进行的操作，提示并跳转到登录
// 添加全局前置守卫

// 需要token 的网页
const authUrl = ['/myorder', '/pay']
router.beforeEach((to, from, next) => {
  // 1. to 往哪里去， 到哪去的路由信息对象
  // 2. from 从哪里来， 从哪来的路由信息对象
  // 3. next() 是否放行
  // 如果next()调用，就是放行
  // next(路径) 拦截到某个路径页面
  // to.path获取去哪的网址
  if (!authUrl.includes(to.path)) {
    // 不是权限页面
    next()
    return
  }
  // 获取token
  const token = store.getters.token
  // 是权限页面判断有无token
  if (!token) {
    // 没有去登陆
    next('/login')
  } else {
    next()
  }
})

export default router
